<!--
 * @Author: quit
 * @Date: 2021-11-17 09:29:35
 * @LastEditTime: 2021-12-17 14:40:09
 * @Descripttion: 寄存器管理
-->
<template>
  <div id="RegisterManagement">
    <div class="app-container" style="height: 100%">
      <el-row :gutter="5">
        <!-- 左侧 -->
        <el-col :span="4" class="left">
          <el-card>
            <div v-loading="treeLoading" class="item-box">
              <el-tree ref="tree" :data="treeData" :props="defaultProps" @node-click="handleNodeClick" />
            </div>
          </el-card>
        </el-col>
        <!-- 右侧 -->
        <el-col :span="20" class="right">
          <el-card>
            <el-row class="right-container">
              <el-col>
                <el-divider content-position="left">搜索信息</el-divider>
                <div class="search">
                  <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
                    <el-form-item :label="'设备名称'">
                      <el-input v-model="searchFrom.dlldrname" disabled :placeholder="'请选择变量名称'" />
                    </el-form-item>
                    <el-form-item :label="'变量名称'">
                      <el-input v-model="searchFrom.itemname" :placeholder="'请选择变量名称'" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-zoom-in" @click="getQstagPage">{{ $t('button.search') }}</el-button>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-refresh-right" @click="refresh">{{ '重置' }}</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
              <el-col class="btns">
                <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItemsBtn">{{ '添加寄存器' }}</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchRemove">{{ $t('button.batchRemove') }}</el-button>
              </el-col>
              <el-col>
                <el-table
                  ref="table"
                  v-loading="loading"
                  :max-height="maxHeight"
                  :data="tableData"
                  :empty-text="$t('table.emptyText')"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" min-width="40" fixed="left" />
                  <el-table-column prop="itemid" label="ID" min-width="80" fixed="left" />
                  <el-table-column prop="itemname" :label="'变量名'" min-width="100" fixed="left" />
                  <el-table-column prop="itemtype" :label="'变量类型'" min-width="80" />
                  <el-table-column prop="itemdradd" :label="'设备地址'" min-width="140" />
                  <el-table-column prop="qstagtype" :label="'寄存器类型'" min-width="70" />
                  <el-table-column prop="qstagadd" :label="'寄存器地址'" min-width="70" />
                  <el-table-column prop="itemxs" :label="'变量系数'" min-width="60" />
                  <el-table-column prop="itemsensitivity" :label="'变化灵敏度'" min-width="70" />
                  <el-table-column prop="itemjqnum" :label="'精确位数'" min-width="60" />
                  <el-table-column prop="dlldrid" :label="'通讯设备'" min-width="60" />
                  <el-table-column prop="itemreadtype" :label="'读写属性'" min-width="60" />
                  <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" min-width="150">
                    <template slot-scope="scope">
                      <el-button type="warning" size="mini" @click="handleEdit(scope.row)">{{ $t('button.edit') }}</el-button>
                      <el-button type="danger" size="mini" @click="handleDetele(scope.row)">{{ $t('button.delete') }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination
                  :current-page.sync="pages.page"
                  :page-sizes="[1, 5, 10, 15]"
                  :page-size.sync="pages.size"
                  layout="prev, pager, next, total, sizes, jumper"
                  :total="pages.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 添加\修改弹出层 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" @close="addDialogClose">
      <el-form ref="dialogFrom" :model="dialogFrom" label-width="100px" class="dialog-from">
        <el-row>
          <el-col :span="11">
            <el-form-item label="变量名">
              <el-input v-model="dialogFrom.itemname" placeholder="请填写变量名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变量类型">
              <el-select v-model="dialogFrom.itemtype" placeholder="请选择变量类型" clearable>
                <el-option v-for="(item, index) in itemtypeData" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="读写类型">
              <el-select v-model="dialogFrom.itemreadtype" placeholder="请选择变量类型" clearable>
                <el-option v-for="(item, index) in itemreadtypeData" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄存器类型">
              <el-select v-model="dialogFrom.qstagtype" placeholder="请选择变量类型" clearable>
                <el-option v-for="(item, index) in qstagtypeData" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="设备地址">
              <el-input v-model="dialogFrom.itemdradd" placeholder="请填写设备地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄存器地址">
              <el-input v-model="dialogFrom.qstagadd" placeholder="请填写寄存器地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left" />
        <el-row>
          <el-col :span="11">
            <el-form-item label="解析类型">
              <el-input v-model="dialogFrom.itemjxtype" placeholder="请填写解析类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变量系数">
              <el-input v-model="dialogFrom.itemxs" placeholder="请填写变量系数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="变化灵敏度">
              <el-input v-model="dialogFrom.itemsensitivity" placeholder="请填写变化灵敏度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="精确位数">
              <el-input v-model="dialogFrom.itemjqnum" placeholder="请填写精确位数">
                <template slot="append">位小数</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="addDialogState === 0" type="primary" @click="sendAddItem">确 定</el-button>
        <el-button v-if="addDialogState === 1" type="primary" @click="sendEditItem">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import { getDeviceAllList, getQstagPage, addQstag, editQstag, delQstagList } from '@/api/BmRequest'

export default {
  components: {},
  data() {
    return {
      treeData: [],
      treeLoading: false,
      defaultProps: { children: 'children', label: 'dlldrname' },
      searchFrom: { itemname: null, dlldrid: null, dlldrname: null },
      maxHeight: null,
      loading: false,
      isCheckedArr: [],
      tableData: [],
      pages: { page: 1, size: 10, total: 0 },
      dialogTitle: '',
      addDialogState: null,
      dialogVisible: false,
      dialogFrom: {
        itemid: null,
        itemname: null,
        itemtype: null,
        itemdradd: null,
        qstagtype: null,
        qstagadd: null,
        itemjxtype: null,
        itemxs: null,
        itemvalue: null,
        itemsensitivity: null,
        itemjqnum: null,
        backtime: null,
        updatetime: null,
        dlldrid: null,
        itemreadtype: null,
        itemnamedescribe: null
      },
      itemtypeData: [
        { label: '离散型', value: 0 },
        { label: '长整型', value: 1 },
        { label: '浮点型', value: 2 },
        { label: '字符串', value: 3 }
      ],
      itemreadtypeData: [
        { label: '只读', value: 0 },
        { label: '读写', value: 1 }
      ],
      qstagtypeData: [{}]
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  created() {
    this.geTreeData()
    this.getQstagPage()
  }, // 生命周期 - 创建完成（可以访问当前this实例）
  mounted() {
    this.setTableHeight()
    window.onresize = () => {
      this.setTableHeight()
    }
  }, // 生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    // 动态设置表格高
    setTableHeight() {
      let num = $('.right-container').height() - 203
      this.maxHeight = num
    },
    /* 左侧树形数据操作 */
    // 获取类型列表
    async geTreeData() {
      this.treeLoading = true
      try {
        const { data } = await getDeviceAllList()
        this.treeData = data
      } catch (error) {
        console.log(error)
      } finally {
        this.treeLoading = false
      }
    },
    // 节点点击事件
    handleNodeClick(data) {
      this.searchFrom.dlldrid = data.dlldrid
      this.searchFrom.dlldrname = data.dlldrname
      this.getQstagPage()
    },

    /* 右侧列表操作 */
    // 获取阈值配置数据列表
    async getQstagPage() {
      const obj = {
        qstag: { itemname: this.searchFrom.itemname, dlldrid: this.searchFrom.dlldrid },
        pages: { page: this.pages.page, size: this.pages.size }
      }
      try {
        this.loading = true
        const { data } = await getQstagPage(obj)
        this.tableData = data.records
        this.pages.page = data.current
        this.pages.size = data.size
        this.pages.total = data.total
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    // 重置按钮
    refresh() {
      this.searchFrom = { itemname: null, dlldrid: null, dlldrname: null }
      this.pages = { page: 1, size: 10, total: 0 }
      this.getQstagPage()
    },

    // 添加按钮
    addItemsBtn() {
      if (!this.searchFrom.dlldrid) {
        this.$message.warning('请先选着需要添加的类型!')
      } else {
        this.addDialogState = 0
        this.dialogTitle = '添加寄存器信息'
        this.dialogFrom.dlldrid = this.searchFrom.dlldrid
        this.dialogVisible = true
      }
    },

    /* table选择事件 */
    handleSelectionChange(val) {
      let nowArr = []
      val.forEach(item => {
        nowArr.push(item.itemid)
      })
      this.isCheckedArr = nowArr
    },

    // 批量删除
    async batchRemove() {
      if (this.isCheckedArr.length > 0) {
        this.$confirm('此操作将删除所选项目, 是否继续?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            if (this.isCheckedArr.length === this.tableData.length) {
              if (this.pages.page > 1) {
                this.pages.page--
              } else {
                this.pages.page = 1
              }
            }
            const { message } = await delQstagList(this.isCheckedArr)
            await this.getQstagPage()
            this.$message.success({ message })
          })
          .catch(error => {
            console.log(error)
            this.$refs.table.clearSelection()
          })
      } else {
        this.$message.warning('请选择需要删除的项目')
      }
    },

    /* 弹出框事件 */
    // 关闭
    addDialogClose() {
      this.dialogFrom = {
        itemid: null,
        itemname: null,
        itemtype: null,
        itemdradd: null,
        qstagtype: null,
        qstagadd: null,
        itemjxtype: null,
        itemxs: null,
        itemvalue: null,
        itemsensitivity: null,
        itemjqnum: null,
        backtime: null,
        updatetime: null,
        dlldrid: null,
        itemreadtype: null,
        itemnamedescribe: null
      }
      this.dialogTitle = null
      this.addDialogState = null
    },
    // 确定
    async sendAddItem() {
      try {
        const { message } = await addQstag(this.dialogFrom)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        this.getQstagPage()
        this.dialogVisible = false
        this.pages.page = Math.ceil(++this.pages.total / this.pages.size)
      }
    },
    // 提交
    async sendEditItem() {
      try {
        const { message } = await editQstag(this.dialogFrom)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        this.dialogVisible = false
        this.getQstagPage()
      }
    },

    /* tabel-item 操作 */
    // 编辑
    handleEdit(data) {
      this.dialogFrom = { ...data }
      this.addDialogState = 1
      this.dialogTitle = '编辑寄存器信息'
      this.dialogVisible = true
    },
    // 删除
    handleDetele(data) {
      this.$confirm('此操作将删除当前项目, 是否继续?', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const nowArr = [data.itemid]
          const { message } = await delQstagList(nowArr)
          if (this.tableData.length === 1) {
            if (this.pages.page > 1) {
              this.pages.page--
            } else {
              this.pages.page = 1
            }
          }
          await this.getQstagPage()
          this.$message.success({ message })
        })
        .catch(error => {
          console.log(error)
        })
    },

    /* 分页操作 */
    // 分页当前页切换
    async handleCurrentChange(newPage) {
      this.pages.page = newPage
      await this.getQstagPage()
    },
    // 分页显示条数切换
    async handleSizeChange(newSize) {
      this.pages.size = newSize
      await this.getQstagPage()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 15px 20px;
}
::v-deep .el-divider {
  margin: 14px 0 !important;
}

.andor-text {
  color: blue;
}

#RegisterManagement {
  .app-container {
    .left {
      .item-box {
        height: calc(100vh - 92px);
        overflow: auto;
        .tree-search {
          margin-bottom: 10px;
        }
      }
    }
    .right {
      .right-container {
        height: calc(100vh - 92px);
        .search {
          border: 1px solid #dcdfe6;
          border-top: none;
          padding: 34px 10px 10px 10px;
          margin-top: -14px;
          .el-input {
            width: 240px;
          }
          .el-button {
            margin-left: 20px;
          }
        }
        .btns {
          padding: 10px 0;
        }
      }
    }
  }
  .dialog-from {
    .el-form-item {
      margin-bottom: 16px;
      position: relative;
    }

    .el-input,
    .el-select,
    .el-textarea {
      width: calc(100% - 10px);
    }

    .color-data {
      display: inline-block;
      position: absolute;
      top: 0;
      height: 40px;
      line-height: 40px;
      padding: 0 0 0 15px;
    }
  }
}
</style>
